package com.kunbo.mathutil;

import org.apache.commons.math3.complex.Complex;
import org.apache.commons.math3.transform.DftNormalization;
import org.apache.commons.math3.transform.FastFourierTransformer;
import org.apache.commons.math3.transform.TransformType;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class FFT{

    private double[] inputData = null;

    private List<Double> frequency = new ArrayList<>();

    public List<Double> start(List<Double> inputData){
        List<Double> result = new ArrayList<>();
        int size = inputData.size();
        double newSize = getNewSize(size);
        //暂时写死，开接口后动态获取
        frequency.clear();
        for(int i = 0; i < newSize; i++){
            frequency.add((i*1000)/newSize);
        }
        System.out.println(frequency.size());
        double[] inputDouble = new double[(int)newSize];
        for(int i = 0; i < size; i++){
            inputDouble[i] = (double)inputData.get(i);
        }
        FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD);
        Complex[] res = fft.transform(inputDouble, TransformType.FORWARD);
        for(Complex c : res){
            double abs = c.abs();
            result.add(abs);
        }
        return result;
    }

    public double getNewSize(int size){
        int i = 0;
        while(size / 2 != 0){
            if(Math.pow(2,i) > size){
                break;
            }
            i++;
        }
        return Math.pow(2,i);
    }

    public List<Double> getFrequency(){
        return frequency;
    }
}

